//
//  HomeTableViewController.swift
//  weibo_swift
//
//  Created by dulinlong on 15/6/23.
//  Copyright © 2015年 sheji_56. All rights reserved.
//

import UIKit
import SVProgressHUD

class HomeTableViewController: BaseTableViewController {

    private var statusList: [Status]? {
        didSet {
            tableView.reloadData()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        vistorView?.setupVistorViewInfo("visitordiscover_feed_image_house", introStr: "关注一些人，回这里看看有什么惊喜", isMain: true)
        
        //用户登录之后再进行一下操作
        if !userLogin  {
         return
        }
        //设置导航
        prepareNavigation()
        //设置tableview
        prepareTableView()
        //设置下拉刷新控件
        prepareRefresh()

    }
    
    override func viewWillAppear(animated: Bool) {
        vistorView?.startAnimation()
    }
    
    override func didReceiveMemoryWarning() {
        heightCache.removeAll()
    }
    

    //从模型加载数据
    func loadData(){
        
        
        //获取最近的一条微博id
        var since_id = statusList?.first?.id ?? 0
        
        var max_id = 0
        if pullUpRefreshTag {
            since_id = 0
            max_id = statusList?.last?.id ?? 0
        }

        Status.loadData(since_id, max_id: max_id ){ (statuses, error) -> () in
            //结束刷新
            self.refreshControl?.endRefreshing()
            
            if error != nil{
                SVProgressHUD.showInfoWithStatus("你的网速不给力")
                return
            }
            
            if statuses == nil{
                print("没有数据传入")
                return
            }
            
            //请求最新数据
            if since_id > 0 {
                self.statusList = statuses! + self.statusList!
            }else if max_id > 0{
                self.statusList = self.statusList! + statuses!
                self.pullUpRefreshTag = false
            }else{
                self.statusList = statuses
            }
            
        }
    }
    
    // MARK: - tableview代理
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statusList?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        //取数据
        let status = statusList![indexPath.item]

        let ID  = StatusCell.cellIndentifier(status)
        let cell = tableView.dequeueReusableCellWithIdentifier(ID, forIndexPath: indexPath) as! StatusCell
        cell.status = statusList![indexPath.item]
        return cell
        
    }
    
    private lazy var heightCache = [Int:CGFloat]()
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        //取数据
        let status = statusList![indexPath.item]
        //获得缓存行高
        if heightCache[status.id] != nil{
            return heightCache[status.id]!
        }
        
        //新建
        let ID  = StatusCell.cellIndentifier(status)
        var cls:AnyClass = StatusNormalCell.self
        if  ID == StatusForwardCellIndentifer{
            cls = StatusForwardCell.self
        }
        
        let cell = cls.new() as! StatusCell
        //行高
        let height = cell.rowHeight(status)
        heightCache[status.id] = height
        //返回行高
        return height
    }
    
    //上拉刷新标志
   private var pullUpRefreshTag = false
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        
        //倒数第二行 将要展示
        if indexPath.item == (statusList?.count)! - 2{
            print("倒数第二行将要展示")
            pullUpRefreshTag = true
            loadData()
        }
    }
    
 
    
    
    // MARK: - navigation上的点击事件
    private let popoverAnimator = PopoverAnimator()
    
    func titleButtonClick(){
        
        let sb = UIStoryboard(name: "FriendGroup", bundle: nil)
        let vc = sb.instantiateInitialViewController()
        vc?.view.backgroundColor = UIColor.clearColor()
        
        //1.设置转场transitoning的代理
        vc?.transitioningDelegate = popoverAnimator
        //1.1设置大小
        let x = (UIScreen.mainScreen().bounds.width - 200) * 0.5
        popoverAnimator.presentFrame = CGRectMake(x, 56, 200, 300)
        //2.设置转场的模式,自定义转场动画
        vc?.modalPresentationStyle = UIModalPresentationStyle.Custom
        
        
        presentViewController(vc!, animated: true, completion: nil)
        
    }
    
     func friendSearchClick(){
        print(__FUNCTION__)
    }
    //二维码点击
     func popClick(){
        let sb = UIStoryboard(name: "QRCode", bundle: nil)
        presentViewController(sb.instantiateInitialViewController()!, animated: true, completion: nil)
    }
    
    //MARK: - 准备工作
    private func prepareNavigation(){
        
        //设置中间的title
        let btn = HomeTitleButton()
        navigationItem.titleView = btn
        btn.addTarget(self, action: "titleButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        

        //设置左边的item
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendsearch", highlightedName: nil, target: self, actionName: "friendSearchClick")

        //设置右边的item
        navigationItem.rightBarButtonItem =  UIBarButtonItem(imageName: "navigationbar_pop", highlightedName: nil, target: self, actionName: "popClick")

        
    }
    
    //设置tableview的相关
    private func prepareTableView(){
        //注册cell
        tableView.registerClass(StatusNormalCell.self, forCellReuseIdentifier: StatusNormalCellIndentifier)
        
        tableView.registerClass(StatusForwardCell.self, forCellReuseIdentifier: StatusForwardCellIndentifer)
        
        //取消分割线
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        
    }
    
    //设置刷新的布局
    private func prepareRefresh(){
        refreshControl = HomeRefreshControl()
        
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
        
        // 开始刷新-不会触发监听方法，会显示刷新控件
        refreshControl?.beginRefreshing()
        
        //加载数据
        loadData()

    }
    
  
}


